import React, { useState, useEffect, useCallback } from 'react';
import {
  Modal,
  Table,
  Space,
  Tag,
  Typography,
  Button,
  Input,
  Select,
  Spin,
  message,
  Tooltip,
  Divider,
  Row,
  Col,
  Card,
  Statistic
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
  FilterOutlined,
  CodeOutlined,
  FileTextOutlined,
  CopyOutlined,
  DownloadOutlined,
  EyeOutlined,
  LinkOutlined,
  GithubOutlined,
  GitlabOutlined
} from '@ant-design/icons';
import { TaskScanResults, getTaskSqlStatementsWithIssues, SqlStatementWithIssues } from '../../services/api';
import './SqlStatementsModal.css';

const { Text } = Typography;
const { Search } = Input;
const { Option } = Select;

interface SqlStatement {
  id: string;
  statementNumber: number;
  content: string;
  type: string; // CREATE, SELECT, INSERT, UPDATE, DELETE, etc.
  sourceFile?: string;
  fileName?: string;
  lineNumber?: number;
  extractionMethod?: string; // MyBatis XML, JPA Annotation, DDL, etc.
  hasIssues?: boolean;
  issueCount?: number;
  databaseType?: string;
  length?: number;
}

interface SqlStatementsModalProps {
  visible: boolean;
  onClose: () => void;
  taskId: number;
  taskName: string;
  scanResults: TaskScanResults | null;
  taskConfig?: any; // 添加任务配置信息
}

const SqlStatementsModal: React.FC<SqlStatementsModalProps> = ({
  visible,
  onClose,
  taskId,
  taskName,
  scanResults,
  taskConfig
}) => {
  const [sqlStatements, setSqlStatements] = useState<SqlStatement[]>([]);
  const [loading, setLoading] = useState(false);
  const [filteredStatements, setFilteredStatements] = useState<SqlStatement[]>([]);
  const [searchKeyword, setSearchKeyword] = useState<string>('');
  const [typeFilter, setTypeFilter] = useState<string>('');
  const [sourceFilter, setSourceFilter] = useState<string>('');
  const [showProblemsOnly, setShowProblemsOnly] = useState(false);
  const [selectedStatement, setSelectedStatement] = useState<SqlStatement | null>(null);
  const [previewVisible, setPreviewVisible] = useState(false);

  // 模拟数据生成（实际应该从API获取）
  const generateMockSqlStatements = useCallback((): SqlStatement[] => {
    const types = ['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'CREATE', 'ALTER', 'DROP'];
    const sources = ['MyBatis XML', 'JPA Annotation', 'Native Query', 'DDL Script'];
    const files = ['UserMapper.xml', 'OrderService.java', 'ProductController.java', 'schema.sql', 'migration.sql'];
    
    // 如果有真实的扫描结果，使用真实的问题数量
    const issueCountMap = new Map<number, number>();
    if (scanResults?.issues) {
      scanResults.issues.forEach(issue => {
        // 优先使用直接的statementNumber字段，然后尝试metadata中的statementNumber
        const statementNumber = issue.statementNumber || issue.metadata?.statementNumber;
        if (statementNumber !== undefined && statementNumber !== null) {
          issueCountMap.set(statementNumber, (issueCountMap.get(statementNumber) || 0) + 1);
        }
      });
    }
    
    return Array.from({ length: scanResults?.sqlStatements || 25 }, (_, index) => {
      const statementNumber = index + 1;
      const type = types[Math.floor(Math.random() * types.length)];
      const source = sources[Math.floor(Math.random() * sources.length)];
      const file = files[Math.floor(Math.random() * files.length)];
      
      // 使用真实的问题数量，如果没有则回退到随机生成
      let issueCount = issueCountMap.get(statementNumber) || 0;
      let hasIssues = issueCount > 0;
      
      // 如果没有真实数据，使用随机生成
      if (issueCountMap.size === 0) {
        hasIssues = Math.random() < 0.3; // 30%的语句有问题
        issueCount = hasIssues ? Math.floor(Math.random() * 3) + 1 : 0;
      }
      
      let content = '';
      switch (type) {
        case 'SELECT':
          content = `SELECT u.id, u.username, u.email, NVL2(u.phone, u.phone, 'N/A') as phone_display,\n       ROWNUM as row_num\nFROM users u\nWHERE u.status = 'active'\n  AND ROWNUM <= 100\nORDER BY u.created_date NULLS LAST`;
          break;
        case 'INSERT':
          content = `INSERT INTO users (id, username, email, password, created_date)\nVALUES (seq_user.NEXTVAL, ?, ?, ?, SYSDATE)`;
          break;
        case 'UPDATE':
          content = `UPDATE users SET \n  last_login_date = SYSDATE,\n  login_count = NVL(login_count, 0) + 1\nWHERE id = ?`;
          break;
        case 'CREATE':
          content = `CREATE TABLE user_profiles (\n  id NUMBER(19) NOT NULL,\n  user_id NUMBER(19) NOT NULL,\n  profile_data CLOB,\n  created_date DATE DEFAULT SYSDATE,\n  CONSTRAINT pk_user_profiles PRIMARY KEY (id)\n)`;
          break;
        default:
          content = `${type} statement example for ${file}`;
      }

      return {
        id: `stmt_${index + 1}`,
        statementNumber: index + 1,
        content,
        type,
        sourceFile: file,
        fileName: file,
        lineNumber: Math.floor(Math.random() * 500) + 1,
        extractionMethod: source,
        hasIssues,
        issueCount,
        databaseType: 'Oracle',
        length: content.length
      };
    });
  }, [scanResults]);

  // 辅助函数：构建Git文件URL
  const buildGitFileUrl = (sourceFile: string, lineNumber?: number): string | null => {
    if (!taskConfig || !sourceFile) return null;
    
    const gitRepositoryUrl = taskConfig.gitRepositoryUrl || taskConfig.repositoryUrl;
    const branchName = taskConfig.branchName || 'master';
    const gitPlatform = taskConfig.gitPlatform || 'gitlab';
    
    if (!gitRepositoryUrl) return null;
    
    try {
      let baseUrl = gitRepositoryUrl;
      
      // 移除 .git 后缀
      if (baseUrl.endsWith('.git')) {
        baseUrl = baseUrl.slice(0, -4);
      }
      
      // 清理sourceFile路径，移除任务编号前缀（如task-79/）
      let filePath = sourceFile.startsWith('/') ? sourceFile.slice(1) : sourceFile;
      
      // 移除任务编号前缀，格式通常是 task-{数字}/
      const taskPrefixPattern = /^task-\d+\//;
      if (taskPrefixPattern.test(filePath)) {
        filePath = filePath.replace(taskPrefixPattern, '');
      }
      
      // 构建文件URL根据不同的Git平台
      let fileUrl = '';
      
      if (gitPlatform.toLowerCase().includes('gitlab') || baseUrl.includes('gitlab')) {
        // GitLab格式: https://gitlab.com/user/repo/-/blob/branch/path/to/file#L123
        fileUrl = `${baseUrl}/-/blob/${branchName}/${filePath}`;
        if (lineNumber) {
          fileUrl += `#L${lineNumber}`;
        }
      } else if (gitPlatform.toLowerCase().includes('github') || baseUrl.includes('github')) {
        // GitHub格式: https://github.com/user/repo/blob/branch/path/to/file#L123
        fileUrl = `${baseUrl}/blob/${branchName}/${filePath}`;
        if (lineNumber) {
          fileUrl += `#L${lineNumber}`;
        }
      } else if (gitPlatform.toLowerCase().includes('gitee') || baseUrl.includes('gitee')) {
        // Gitee格式: https://gitee.com/user/repo/blob/branch/path/to/file#L123
        fileUrl = `${baseUrl}/blob/${branchName}/${filePath}`;
        if (lineNumber) {
          fileUrl += `#L${lineNumber}`;
        }
      } else {
        // 默认使用GitLab格式
        fileUrl = `${baseUrl}/-/blob/${branchName}/${filePath}`;
        if (lineNumber) {
          fileUrl += `#L${lineNumber}`;
        }
      }
      
      return fileUrl;
    } catch (error) {
      console.warn('构建Git文件URL失败:', error);
      return null;
    }
  };

  // 辅助函数：获取Git平台图标
  const getGitPlatformIcon = (gitUrl: string): React.ReactNode => {
    if (!gitUrl) return <LinkOutlined />;
    
    if (gitUrl.includes('gitlab')) {
      return <GitlabOutlined style={{ color: '#FC6D26' }} />;
    } else if (gitUrl.includes('github')) {
      return <GithubOutlined style={{ color: '#181717' }} />;
    } else if (gitUrl.includes('gitee')) {
      return <GithubOutlined style={{ color: '#C71D23' }} />;
    }
    return <LinkOutlined />;
  };

  // 辅助函数：转换来源类型显示文本
  const getExtractionMethodDisplay = (sourceType: string): string => {
    switch (sourceType) {
      case 'MYBATIS_XML': return 'MyBatis XML';
      case 'MYBATIS_ANNOTATION': return 'MyBatis Annotation';
      case 'JPA_ANNOTATION': return 'JPA Annotation';
      case 'NATIVE_QUERY': return 'Native Query';
      case 'MANUAL_INPUT': return 'Manual Input';
      case 'DDL_SCRIPT': return 'DDL Script';
      default: return sourceType;
    }
  };

  const loadSqlStatements = useCallback(async () => {
    setLoading(true);
    try {
      const response = await getTaskSqlStatementsWithIssues(taskId);
      if (response.success) {
        // 直接使用后端返回的带问题统计的数据
        const convertedStatements: SqlStatement[] = response.data.map(stmt => {
          return {
            id: stmt.statementNumber.toString(),
            statementNumber: stmt.statementNumber,
            content: stmt.sqlContent || '',
            type: stmt.sqlType,
            sourceFile: stmt.sourceFile,
            fileName: stmt.sourceFile ? stmt.sourceFile.split('/').pop() : 'Unknown',
            lineNumber: stmt.lineNumber,
            extractionMethod: getExtractionMethodDisplay(stmt.sourceType),
            hasIssues: stmt.hasIssues,
            issueCount: stmt.issueCount,
            databaseType: 'Unknown',
            length: (stmt.sqlContent || '').length
          };
        });
        
        setSqlStatements(convertedStatements);
      } else {
        message.error('获取SQL语句失败: ' + response.message);
        // 降级使用模拟数据
        const mockStatements = generateMockSqlStatements();
        setSqlStatements(mockStatements);
      }
    } catch (error: any) {
      console.error('加载SQL语句失败:', error);
      message.error('加载SQL语句失败，使用模拟数据: ' + error.message);
      // 降级使用模拟数据
      const mockStatements = generateMockSqlStatements();
      setSqlStatements(mockStatements);
    } finally {
      setLoading(false);
    }
  }, [taskId, generateMockSqlStatements]);

  useEffect(() => {
    if (visible) {
      loadSqlStatements();
    }
  }, [visible, taskId, scanResults, loadSqlStatements]);

  const applyFilters = useCallback(() => {
    let filtered = sqlStatements;

    // 关键词搜索
    if (searchKeyword.trim()) {
      filtered = filtered.filter(stmt => 
        stmt.content.toLowerCase().includes(searchKeyword.toLowerCase()) ||
        stmt.fileName?.toLowerCase().includes(searchKeyword.toLowerCase()) ||
        stmt.type.toLowerCase().includes(searchKeyword.toLowerCase())
      );
    }

    // 语句类型过滤
    if (typeFilter) {
      filtered = filtered.filter(stmt => stmt.type === typeFilter);
    }

    // 来源过滤
    if (sourceFilter) {
      filtered = filtered.filter(stmt => stmt.extractionMethod === sourceFilter);
    }

    // 仅显示有问题的语句
    if (showProblemsOnly) {
      filtered = filtered.filter(stmt => stmt.hasIssues);
    }

    setFilteredStatements(filtered);
  }, [sqlStatements, searchKeyword, typeFilter, sourceFilter, showProblemsOnly]);

  useEffect(() => {
    applyFilters();
  }, [applyFilters]);

  const handleCopyStatement = (statement: SqlStatement) => {
    navigator.clipboard.writeText(statement.content);
    message.success('SQL语句已复制到剪贴板');
  };

  const handlePreviewStatement = (statement: SqlStatement) => {
    setSelectedStatement(statement);
    setPreviewVisible(true);
  };

  const getStatementTypeColor = (type: string) => {
    const colors: Record<string, string> = {
      'SELECT': 'blue',
      'INSERT': 'green',
      'UPDATE': 'orange',
      'DELETE': 'red',
      'CREATE': 'purple',
      'ALTER': 'cyan',
      'DROP': 'magenta'
    };
    return colors[type] || 'default';
  };

  const getExtractionMethodIcon = (method?: string) => {
    switch (method) {
      case 'MyBatis XML': return '📄';
      case 'JPA Annotation': return '☕';
      case 'Native Query': return '⚡';
      case 'DDL Script': return '🗃️';
      default: return '📝';
    }
  };

  const columns: ColumnsType<SqlStatement> = [
    {
      title: '#',
      dataIndex: 'statementNumber',
      key: 'statementNumber',
      width: 60,
      sorter: (a: SqlStatement, b: SqlStatement) => a.statementNumber - b.statementNumber,
    },
    {
      title: '语句类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: string) => (
        <Tag color={getStatementTypeColor(type)}>{type}</Tag>
      ),
      filters: Array.from(new Set(sqlStatements.map(s => s.type))).map(type => ({
        text: type,
        value: type,
      })),
      onFilter: (value: any, record: SqlStatement) => record.type === value,
    },
    {
      title: 'SQL预览',
      dataIndex: 'content',
      key: 'content',
      ellipsis: true,
      render: (content: string, record: SqlStatement) => (
        <div className="sql-content-preview">
          <Text className="sql-preview-text" style={{ fontFamily: 'monospace', fontSize: '12px' }}>
            {content.length > 100 ? `${content.substring(0, 100)}...` : content}
          </Text>
          <div className="sql-preview-actions">
            <Tooltip title="预览完整SQL">
              <Button 
                type="link" 
                icon={<EyeOutlined />} 
                size="small"
                onClick={() => handlePreviewStatement(record)}
              />
            </Tooltip>
            <Tooltip title="复制SQL">
              <Button 
                type="link" 
                icon={<CopyOutlined />} 
                size="small"
                onClick={() => handleCopyStatement(record)}
              />
            </Tooltip>
          </div>
        </div>
      ),
    },
    {
      title: '来源文件',
      dataIndex: 'fileName',
      key: 'fileName',
      width: 180,
      ellipsis: true,
      render: (fileName: string, record: SqlStatement) => {
        const gitFileUrl = buildGitFileUrl(record.sourceFile || '', record.lineNumber);
        const gitRepositoryUrl = taskConfig?.gitRepositoryUrl || taskConfig?.repositoryUrl;
        
        return (
          <Space direction="vertical" size={0}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
              {gitFileUrl ? (
                <Tooltip title={`在Git平台中查看文件 (行 ${record.lineNumber})`}>
                  <Button
                    type="link"
                    size="small"
                    icon={getGitPlatformIcon(gitRepositoryUrl)}
                    onClick={() => window.open(gitFileUrl, '_blank')}
                    style={{ 
                      padding: '0 4px', 
                      height: 'auto', 
                      fontSize: '12px',
                      display: 'flex',
                      alignItems: 'center'
                    }}
                  >
                    <Text ellipsis style={{ maxWidth: 120, fontSize: '12px' }}>{fileName}</Text>
                  </Button>
                </Tooltip>
              ) : (
                <Text ellipsis style={{ maxWidth: 160, fontSize: '12px' }}>{fileName}</Text>
              )}
            </div>
            <Text type="secondary" style={{ fontSize: 11 }}>
              行 {record.lineNumber}
              {gitFileUrl && (
                <Tooltip title="点击文件名可跳转到Git平台">
                  <LinkOutlined style={{ marginLeft: 4, fontSize: 10, color: '#1890ff' }} />
                </Tooltip>
              )}
            </Text>
          </Space>
        );
      },
    },
    {
      title: '提取方式',
      dataIndex: 'extractionMethod',
      key: 'extractionMethod',
      width: 130,
      render: (method: string) => (
        <Space size={4}>
          <span>{getExtractionMethodIcon(method)}</span>
          <Text style={{ fontSize: 11 }}>{method}</Text>
        </Space>
      ),
      filters: Array.from(new Set(sqlStatements.map(s => s.extractionMethod).filter(Boolean))).map(method => ({
        text: method!,
        value: method!,
      })),
      onFilter: (value: any, record: SqlStatement) => record.extractionMethod === value,
    },
    {
      title: '问题',
      key: 'issues',
      width: 80,
      render: (_: any, record: SqlStatement) => (
        <div style={{ textAlign: 'center' }}>
          {record.hasIssues ? (
            <Tag color="red">{record.issueCount}</Tag>
          ) : (
            <Tag color="green">0</Tag>
          )}
        </div>
      ),
      sorter: (a: SqlStatement, b: SqlStatement) => (a.issueCount || 0) - (b.issueCount || 0),
    },
    {
      title: '长度',
      dataIndex: 'length',
      key: 'length',
      width: 80,
      render: (length: number) => (
        <Text type="secondary" style={{ fontSize: 11 }}>{length} 字符</Text>
      ),
      sorter: (a: SqlStatement, b: SqlStatement) => (a.length || 0) - (b.length || 0),
    }
  ];

  const renderStatistics = () => {
    const typeStats = sqlStatements.reduce((acc, stmt) => {
      acc[stmt.type] = (acc[stmt.type] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);

    const problemStatementsCount = sqlStatements.filter(s => s.hasIssues).length;
    const totalIssueCount = sqlStatements.reduce((sum, s) => sum + (s.issueCount || 0), 0);

    return (
      <Card size="small" className="sql-statistics-card">
        <Row gutter={[16, 8]}>
          <Col span={6}>
            <Statistic
              title="总语句数"
              value={sqlStatements.length}
              valueStyle={{ fontSize: 16, color: '#1890ff' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="有问题语句"
              value={problemStatementsCount}
              valueStyle={{ fontSize: 16, color: problemStatementsCount > 0 ? '#ff4d4f' : '#52c41a' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="总问题数"
              value={totalIssueCount}
              valueStyle={{ fontSize: 16, color: '#fa8c16' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="问题率"
              value={sqlStatements.length > 0 ? Math.round((problemStatementsCount / sqlStatements.length) * 100) : 0}
              suffix="%"
              valueStyle={{ fontSize: 16, color: problemStatementsCount > 0 ? '#ff4d4f' : '#52c41a' }}
            />
          </Col>
        </Row>
        
        <Divider style={{ margin: '12px 0' }} />
        
        <div className="statement-type-distribution">
          <Text strong style={{ fontSize: 12, color: '#666' }}>语句类型分布：</Text>
          <Space wrap style={{ marginTop: 4 }}>
            {Object.entries(typeStats).map(([type, count]) => (
              <Tag key={type} color={getStatementTypeColor(type)}>
                {type}: {count}
              </Tag>
            ))}
          </Space>
        </div>
      </Card>
    );
  };

  const renderFilters = () => (
    <Card size="small" className="sql-filters-card">
      <Row gutter={[12, 8]} align="middle">
        <Col flex="auto">
          <Search
            placeholder="搜索SQL内容、文件名或语句类型..."
            value={searchKeyword}
            onChange={(e) => setSearchKeyword(e.target.value)}
            style={{ width: '100%' }}
            allowClear
          />
        </Col>
        <Col>
          <Select
            placeholder="语句类型"
            value={typeFilter}
            onChange={setTypeFilter}
            style={{ width: 120 }}
            allowClear
          >
            {Array.from(new Set(sqlStatements.map(s => s.type))).map(type => (
              <Option key={type} value={type}>{type}</Option>
            ))}
          </Select>
        </Col>
        <Col>
          <Select
            placeholder="提取方式"
            value={sourceFilter}
            onChange={setSourceFilter}
            style={{ width: 140 }}
            allowClear
          >
            {Array.from(new Set(sqlStatements.map(s => s.extractionMethod))).map(method => (
              <Option key={method} value={method}>{method}</Option>
            ))}
          </Select>
        </Col>
        <Col>
          <Button 
            type={showProblemsOnly ? 'primary' : 'default'}
            icon={<FilterOutlined />}
            onClick={() => setShowProblemsOnly(!showProblemsOnly)}
          >
            仅问题语句
          </Button>
        </Col>
      </Row>
    </Card>
  );

  return (
    <>
      <Modal
        title={
          <Space>
            <CodeOutlined />
            <span>SQL语句详情 - {taskName}</span>
            <Tag color="blue">{filteredStatements.length} / {sqlStatements.length}</Tag>
          </Space>
        }
        open={visible}
        onCancel={onClose}
        width={1200}
        footer={[
          <Button key="export" icon={<DownloadOutlined />}>
            导出列表
          </Button>,
          <Button key="close" onClick={onClose}>
            关闭
          </Button>
        ]}
        className="sql-statements-modal"
      >
        <Spin spinning={loading}>
          <div className="sql-statements-content">
            {!loading && sqlStatements.length > 0 && (
              <>
                {renderStatistics()}
                {renderFilters()}
                <Table
                  columns={columns}
                  dataSource={filteredStatements}
                  rowKey="id"
                  size="small"
                  pagination={{
                    pageSize: 10,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`,
                  }}
                  scroll={{ y: 400 }}
                  className="sql-statements-table"
                />
              </>
            )}
            
            {!loading && sqlStatements.length === 0 && (
              <div className="no-data-placeholder">
                <FileTextOutlined style={{ fontSize: 48, color: '#d9d9d9' }} />
                <Text type="secondary">暂无SQL语句数据</Text>
              </div>
            )}
          </div>
        </Spin>
      </Modal>

      {/* SQL预览模态框 */}
      <Modal
        title={
          <Space>
            <EyeOutlined />
            <span>SQL语句预览</span>
            {selectedStatement && (
              <Tag color={getStatementTypeColor(selectedStatement.type)}>
                {selectedStatement.type}
              </Tag>
            )}
          </Space>
        }
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        width={800}
        footer={[
          <Button 
            key="copy" 
            icon={<CopyOutlined />}
            onClick={() => selectedStatement && handleCopyStatement(selectedStatement)}
          >
            复制
          </Button>,
          <Button key="close" onClick={() => setPreviewVisible(false)}>
            关闭
          </Button>
        ]}
      >
        {selectedStatement && (
          <div className="sql-preview-content">
            <div className="sql-info-header">
              <Space direction="vertical" size={4}>
                <Text strong>{selectedStatement.fileName}</Text>
                <Text type="secondary" style={{ fontSize: 11 }}>
                  行 {selectedStatement.lineNumber} | {selectedStatement.extractionMethod}
                </Text>
              </Space>
            </div>
            <Divider style={{ margin: '12px 0' }} />
            <div className="sql-preview-text-container" style={{ 
              background: '#f5f5f5', 
              padding: '12px', 
              borderRadius: '6px',
              fontFamily: 'monospace',
              fontSize: '12px',
              lineHeight: '1.6',
              whiteSpace: 'pre-wrap',
              color: '#333',
              border: '1px solid #d9d9d9'
            }}>
              {selectedStatement.content}
            </div>
            {selectedStatement.hasIssues && (
              <div className="sql-issues-info">
                <Text type="warning">
                  ⚠️ 此SQL语句存在 {selectedStatement.issueCount} 个兼容性问题
                </Text>
              </div>
            )}
          </div>
        )}
      </Modal>
    </>
  );
};

export default SqlStatementsModal;